from pyecharts import options as opts
from pyecharts.charts import Boxplot, Scatter, Grid
from kit import *


def box_scatter(all_data):
    box_plot = Boxplot()  # 这个使得两个箱线图重合
    box_plot = (
        box_plot
            .add_xaxis(xaxis_data=all_data.row_values(0)[1:])
            .set_global_opts(
            title_opts=opts.TitleOpts(
                pos_left="left", title="居左的标题"
            ),
            xaxis_opts=opts.AxisOpts(
                type_="category",
                boundary_gap=True,
                splitline_opts=opts.SplitLineOpts(is_show=False),  # 分割线显示与否
            ),
            yaxis_opts=opts.AxisOpts(  # y轴
                type_="value",
                name="km/s minus 299,000",
                splitarea_opts=opts.SplitAreaOpts(
                    is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)
                ),
            ),
        )
            .set_series_opts(tooltip_opts=opts.TooltipOpts(formatter="{b}: {c}"))  # 按照名称/最小值/Q1/中值/Q3/最大值 展示
    )

    scatter_data = []
    for i in range(1, all_data.nrows):
        v = manage_data_to_box(all_data.row_values(i)[1:])
        box_plot.add_yaxis(all_data.row_values(i)[0], box_plot.prepare_data(v))
        mid_data = []
        for j in range(0, len(v)):
            mid_data.append(sum(v[j]) / len(v[j]))
        scatter_data.append(sum(mid_data) / len(mid_data))

    scatter = (
        Scatter()
            .add_xaxis(xaxis_data=all_data.row_values(0)[1:])
            .add_yaxis(series_name="", y_axis=scatter_data)
            .set_global_opts(
            title_opts=opts.TitleOpts(  # 标题
                pos_left="10%",
                pos_top="90%",
                title="upper: Q3 + 1.5 * IQR \n\nlower: Q1 - 1.5 * IQR",
                title_textstyle_opts=opts.TextStyleOpts(
                    border_color="#999", border_width=1, font_size=14
                ),
            ),
            yaxis_opts=opts.AxisOpts(
                axislabel_opts=opts.LabelOpts(is_show=False),
                axistick_opts=opts.AxisTickOpts(is_show=False),
            ),
        )
    )
    grid = (
        Grid(init_opts=opts.InitOpts(width="1000px", height="600px"))  # 设置长宽

            .add(
            box_plot,
            grid_opts=opts.GridOpts(pos_left="10%", pos_right="10%", pos_bottom="15%"),
        )

            .add(
            scatter,
            grid_opts=opts.GridOpts(pos_left="10%", pos_right="10%", pos_bottom="15%"),
        )

    )
    grid.set_global_opts(title_opts=opts.TitleOpts(title=all_data.name),
                         toolbox_opts=opts.ToolboxOpts(),
                         datazoom_opts=opts.DataZoomOpts(range_start=1, range_end=300)
                         )
    grid.render("boxplot_light_velocity.html")
